package com.myproject.exception;

import com.myproject.enums.ErrorCode;
import com.myproject.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 业务异常处理
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<ErrorResponse> handleBusinessException(BusinessException ex) {
        log.warn("业务异常: code={}, msg={}", ex.getCode(), ex.getMessage());
        return Result.error(ex.getCode(), ex.getMessage());
    }

    // 验证异常处理
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<ErrorResponse> handleValidationException(Exception ex) {
        List<String> errors = new ArrayList<>();
        if (ex instanceof MethodArgumentNotValidException validEx) {
            validEx.getBindingResult().getFieldErrors()
                   .forEach(fieldError -> errors.add(fieldError.getDefaultMessage()));
        } else if (ex instanceof BindException bindEx) {
            bindEx.getFieldErrors().forEach(fieldError -> errors.add(fieldError.getDefaultMessage()));
        }
        log.info("参数校验失败: {}", errors);
        return Result.error(ErrorCode.VALIDATION_ERROR, "参数错误", errors);
    }

    // 404处理
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Result<ErrorResponse> handleNotFound(NoHandlerFoundException ex) {
        log.warn("资源未找到: {}", ex.getRequestURL());
        return Result.error(ErrorCode.NOT_FOUND, "请求资源不存在");
    }

    // 全局异常处理
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<ErrorResponse> handleAllExceptions(Exception ex, WebRequest request) {
        String message = isProduction() ? "系统繁忙，请稍后再试" : ex.getMessage();
        log.error("系统异常: {}", ex.getMessage(), ex); // 记录堆栈
        return Result.error(ErrorCode.SYSTEM_ERROR, message);
    }

    private boolean isProduction() {
        return "prod".equals(System.getProperty("env"));
    }
}